﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using dotnetCHARTING.WinForms;
using System.Collections;
using System.Drawing.Drawing2D;
using ViCode_LeVi.Controls.Logs;
using ViCode_LeVi.Configs;
using ViCode_LeVi.Data;
namespace ViCode_LeVi.Controls.Charts
{
    public partial class BarChartQQS : ChartCtrl
    {
        private FactorProperty[] m_aFactorProperties;
        private FactorType m_eFilterFactorType = FactorType.HK;
        private int m_iCountQuality;
        private int m_iCountQuantity;
        private int m_iCountSystematic;

        public BarChartQQS()
        {
            this.InitializeComponent();
        }

        private void AddElementToSeries(ref Series oSeries, double dValue, FactorProperty oFactorProperty)
        {
            try
            {
                string str;
                Element element = new Element();
                switch (base.ChartLabelMode)
                {
                    case eChartLabelMode.Full:
                        element.Name = oFactorProperty.Id + ": " + oFactorProperty.Name;
                        goto Label_017A;

                    case eChartLabelMode.FullWithValue:
                        if ((dValue != BTB_DH.INVALID_DOUBLE) && (dValue >= 0.0))
                        {
                            element.ShowValue = true;
                            if ((dValue % 1.0) != 0.0)
                            {
                                break;
                            }
                            element.SmartLabel.Text = dValue + "%";
                        }
                        goto Label_00BA;

                    case eChartLabelMode.Short:
                        element.Name = oFactorProperty.Id;
                        goto Label_017A;

                    case eChartLabelMode.ShortWithValue:
                        if ((dValue != BTB_DH.INVALID_DOUBLE) && (dValue >= 0.0))
                        {
                            element.ShowValue = true;
                            if ((dValue % 1.0) != 0.0)
                            {
                                goto Label_013D;
                            }
                            element.SmartLabel.Text = dValue + "%";
                        }
                        goto Label_015E;

                    default:
                        element.Name = oFactorProperty.Id;
                        goto Label_017A;
                }
                element.SmartLabel.Text = dValue.ToString("0.00") + "%";
            Label_00BA:
                element.Name = oFactorProperty.Id + ": " + oFactorProperty.Name;
                goto Label_017A;
            Label_013D:
                element.SmartLabel.Text = dValue.ToString("0.00") + "%";
            Label_015E:
                element.Name = oFactorProperty.Id;
            Label_017A:
                str = string.Empty;
                switch (base.ChartToolTipMode)
                {
                    case eChartToolTipMode.Full:
                        element.ToolTip = oFactorProperty.Name;
                        goto Label_025A;

                    case eChartToolTipMode.Percent:
                        if (dValue < 0.0)
                        {
                            goto Label_023C;
                        }
                        str = dValue + "%";
                        goto Label_0242;

                    case eChartToolTipMode.FullPercent:
                        if (dValue < 0.0)
                        {
                            break;
                        }
                        str = dValue + "%";
                        goto Label_01D9;

                    default:
                        goto Label_025A;
                }
                str = "-";
            Label_01D9: ;
                element.ToolTip = oFactorProperty.Name + ", " + oSeries.Name + ": " + str;
                goto Label_025A;
            Label_023C:
                str = "-";
            Label_0242:
                element.ToolTip = oSeries.Name + ": " + str;
            Label_025A:
                if ((dValue < 0.0) || (dValue == BTB_DH.INVALID_INT))
                {
                    element.YValue = 0.0;
                }
                else if (dValue == 0.0)
                {
                    element.YValue = Convert.ToDouble(base.chart1.XAxis.Maximum) / 250.0;
                }
                else
                {
                    element.YValue = dValue;
                }
                oSeries.Elements.Add(element);
            }
            catch (Exception exception)
            {
                Log.LogException(exception);
            }
        }
        
        new string GetFilterFactorTypeNames()
        {
            Step_TaskItemGroup[] grps = Func_GetStep_TaskItemGroup == null ? null : Func_GetStep_TaskItemGroup();
            if (grps == null)
                return string.Empty ;

            StringBuilder sb = new StringBuilder();
            foreach(var grp in grps)
            {
                sb.AppendFormat("{0} ", grp.Name);
            }
            return sb.ToString().Trim();
            //string str = "";
            //try
            //{
            //    if (this.FilterFactorTypeHK)
            //    {
            //        str = str + RootData.Intance.Report_SucessFactor_Human;// "Human Capital,";
            //    }
            //    if (this.FilterFactorTypeSK)
            //    {
            //        str = str + RootData.Intance.Report_SucessFactor_Structural;//"Structural Capital,";
            //    }
            //    if (this.FilterFactorTypeBK)
            //    {
            //        str = str + RootData.Intance.Report_SucessFactor_Relational;//"Relational Capital,";
            //    }
            //    if (str.EndsWith(","))
            //    {
            //        str = str.Remove(str.Length - 1, 1);
            //    }
            //}
            //catch (Exception exception)
            //{
            //    Log.LogException(exception);
            //}
            //return str;
        }
        public override bool CreateChart()
        {
            LegendBox legendBox = null;
            bool flag = true;
            int riNumberOfElements = 0;
            try
            {
                base.SetChartBasis(eChartType.BarChartQQS, base.m_sXAxisLabel, base.m_sYAxisLabel);
                base.chart1.Title = string.Format("{0} ({1})", ProjectData.Intance.Period.Tab6_Evaluation_Analysis_2, GetFilterFactorTypeNames()/*base.GetFilterFactorTypeNames()*/);
                base.chart1.SeriesCollection.Clear();
                base.chart1.ExtraLegendBoxes.Clear();
                base.chart1.ExtraLegendEntries.Clear();
                base.chart1.XAxis.Markers.Clear();
                base.chart1.YAxis.Markers.Clear();
                if (VMConfig.Intance.Charts.LimitBarChartBarWidth)
                {
                    base.chart1.YAxis.StaticColumnWidth = ((float)((VMConfig.Intance.Charts.MaxBarChartBarWidth * 3) * base.ChartDPI)) / 96f;
                }
                else
                {
                    base.chart1.YAxis.StaticColumnWidth = 0f;
                }
                base.chart1.XAxis.DefaultTick.Label.Text = "%Value%";
                SeriesCollection seriesCollection = this.SetData(ref riNumberOfElements);
                base.NumberOfElements = riNumberOfElements;
                if (base.NumberOfElements > 0)
                {
                    base.chart1.SeriesCollection.Add(seriesCollection);
                    if (base.ChartLegendMode != eChartLegendMode.None)
                    {
                        legendBox = this.GetExtraLegendBox(this.m_aFactorProperties);
                        base.chart1.ExtraLegendBoxes.Add(legendBox);
                    }
                }
                else
                {
                    Series series = new Series("Empty")
                    {
                        LegendEntry = { Visible = true, Value = "" }
                    };
                    series.LegendEntry.LabelStyle.Color = Color.Empty;
                    Element element = new Element
                    {
                        Name = string.Empty,
                        YValue = 15.0,
                        Transparency = 100,
                        Color = Color.Empty
                    };
                    series.Elements.Add(element);
                    base.chart1.SeriesCollection.Add(series);
                }
                base.chart1.XAxis.Interval = 10.0;
                base.chart1.XAxis.Minimum = 0;
                base.chart1.XAxis.Maximum = 0x66;
                base.GetAxisMarkers(base.chart1.XAxis);
                base.chart1.RefreshChart();
            }
            catch (Exception exception)
            {
                flag = false;
                //rsErr = "Fehler in BarChartQQS.CreateChart: " + exception.Message;
                Log.LogException(exception);
            }
            return flag;
        }        

        private LegendBox GetExtraLegendBox(FactorProperty[] aFactorProperties)
        {
            bool flag = true;
            LegendBox box = new LegendBox();
            int count = 0;
            string psLegendEntryText = string.Empty;
            try
            {
                box.Background = base.chart1.TitleBox.Background;
                box.CornerBottomRight = BoxCorner.Square;
                box.CornerBottomLeft = BoxCorner.Square;
                box.CornerTopLeft = BoxCorner.Square;
                box.CornerTopRight = BoxCorner.Square;
                box.LabelStyle = new dotnetCHARTING.WinForms.Label("", new Font("Arial", 8f), Color.Black);
                box.Line = new Line(Color.Black);
                box.Shadow.Soft = true;
                box.Shadow.Color = Color.Gray;
                box.Shadow.Depth = 5;
                box.ListTopToBottom = true;
                box.Orientation = base.ExtraLegendBoxOrientation;
                if (aFactorProperties != null)
                {
                    count = aFactorProperties.Length;
                    foreach (FactorProperty property in aFactorProperties)
                    {
                        box.Template = "%CustomToken";
                        box.ColumnAlignments = new StringAlignment[1];
                        switch (base.ChartLegendMode)
                        {
                            case eChartLegendMode.Full:
                                psLegendEntryText = string.Format("{0}: {1}", property.Id, property.Name);
                                break;

                            case eChartLegendMode.Short:
                                psLegendEntryText = property.Id;
                                break;
                        }
                        if (base.LegendWithPercent)
                        {
                            string str2 = string.Empty;
                            string str3 = string.Empty;
                            string str4 = string.Empty;
                            if (property.Quantity < 0.0)
                            {
                                str2 = " - ";
                            }
                            else if ((property.Quantity % 1.0) == 0.0)
                            {
                                str2 = property.Quantity + "%";
                            }
                            else
                            {
                                str2 = property.Quantity.ToString("0.00") + "%";
                            }
                            if (property.Quality < 0.0)
                            {
                                str3 = " - ";
                            }
                            else if ((property.Quality % 1.0) == 0.0)
                            {
                                str3 = property.Quality + "%";
                            }
                            else
                            {
                                str3 = property.Quality.ToString("0.00") + "%";
                            }
                            if (property.Systematic < 0.0)
                            {
                                str4 = " - ";
                            }
                            else if ((property.Systematic % 1.0) == 0.0)
                            {
                                str4 = property.Systematic + "%";
                            }
                            else
                            {
                                str4 = property.Systematic.ToString("0.00") + "%";
                            }
                            psLegendEntryText = psLegendEntryText + string.Format(" (Qn:{0} Ql:{1} Sy:{2})", str2, str3, str4);
                        }
                        LegendEntry legendEntry = new LegendEntry("", "")
                        {
                            SortOrder = count
                        };
                        legendEntry.CustomAttributes.Add("CustomToken", base.FormatLegendEntryText(psLegendEntryText));
                        box.ExtraEntries.Add(legendEntry);
                        count--;
                    }
                }
                return box;
            }
            catch (Exception exception)
            {
                flag = false;
                Log.LogException(exception);
            }
            finally
            {
                if (!flag)
                {
                    box.ExtraEntries.Clear();
                }
            }
            return box;
        }
        public Func<Step_TaskItemGroup[]> Func_GetStep_TaskItemGroup;
        private FactorProperty[] GetFactorProperties()
        {
            bool flag = true;
            bool filterFactorTypeHK = false;
            List<FactorProperty> list = new List<FactorProperty>();
            Step_TaskItemGroup[] grps = Func_GetStep_TaskItemGroup == null ? null : Func_GetStep_TaskItemGroup();
            if (grps == null)
                return new FactorProperty[0];
            foreach (var group in grps)
            {
                var data = group.Tasks_Source.Select(c => new FactorProperty()
                {
                    Quality = c.Quanlity_WeightPercent.HasValue == false ? 0 : (double)c.Quanlity_WeightPercent.Value
                     ,
                    Quantity = c.Quantity_WeightPercent.HasValue == false ? 0 : (double)c.Quantity_WeightPercent.Value
                     ,
                    Systematic = c.Systematic_WeightPercent.HasValue == false ? 0 : (double)c.Systematic_WeightPercent.Value
                     ,
                    Importance = c.Weight
                     ,
                    Name = c.Name
                     ,
                    XPercent = 0
                     ,
                    YPercent = 0
                     ,
                    Id = c.ID,
                    BubblePercent = 0,
                    BubbleSize = (c.Systematic_WeightPercent.HasValue == false ? 0 : (double)c.Systematic_WeightPercent.Value) + 25,
                    Marker = string.Empty
                     ,
                    XPotential = c.Quanlity_WeightPercent.HasValue == false ? 0 : (double)c.Quanlity_WeightPercent.Value
                     ,
                    YPotential = c.Weight
                     ,
                    Type = group.FactorType
                     ,
                    ImportancePercent = 0
                     ,
                    EvaluatedDimensions = 50
                }).ToArray();
                list.AddRange(data);
            }
            //FactorProperty property = new FactorProperty();
            //QQSRecord record = null;
            //int num = 0;
            //int num2 = 0;
            //int num3 = 0;
            //try
            //{
            //    if (oProject != null)
            //    {
            //        FactorList list2 = oProject.ValidFactorsForCurrentPeriod(true);
            //        if (list2 != null)
            //        {
            //            foreach (Factor factor in list2)
            //            {
            //                if (((factor == null) || (factor.Type == FactorType.GE)) || ((factor.Type == FactorType.GP) || (factor.Type == FactorType.UNKNOWN)))
            //                {
            //                    continue;
            //                }
            //                record = factor.QQSForPeriod(oProject.CurrentPeriod);
            //                if (record == null)
            //                {
            //                    continue;
            //                }
            //                FactorType type = factor.Type;
            //                if (type != FactorType.HK)
            //                {
            //                    if (type == FactorType.SK)
            //                    {
            //                        goto Label_00B8;
            //                    }
            //                    if (type == FactorType.BK)
            //                    {
            //                        goto Label_00C1;
            //                    }
            //                    goto Label_00CA;
            //                }
            //                filterFactorTypeHK = base.FilterFactorTypeHK;
            //                goto Label_00CC;
            //            Label_00B8:
            //                filterFactorTypeHK = base.FilterFactorTypeSK;
            //                goto Label_00CC;
            //            Label_00C1:
            //                filterFactorTypeHK = base.FilterFactorTypeBK;
            //                goto Label_00CC;
            //            Label_00CA:
            //                filterFactorTypeHK = false;
            //            Label_00CC:
            //                if (filterFactorTypeHK)
            //                {
            //                    property = new FactorProperty
            //                    {
            //                        Id = factor.LogicalID,
            //                        Name = factor.Name,
            //                        Type = factor.Type
            //                    };
            //                    if (record.QualityUsed && (record.QualityAsIs != DH.INVALID_INT))
            //                    {
            //                        property.Quality = record.QualityAsIs;
            //                        num++;
            //                    }
            //                    else
            //                    {
            //                        property.Quality = -1.0;
            //                    }
            //                    if (record.QuantityUsed && (record.QuantityAsIs != DH.INVALID_INT))
            //                    {
            //                        property.Quantity = record.QuantityAsIs;
            //                        num2++;
            //                    }
            //                    else
            //                    {
            //                        property.Quantity = -1.0;
            //                    }
            //                    if (record.SystematicsUsed && (record.SystematicsAsIs != DH.INVALID_INT))
            //                    {
            //                        property.Systematic = record.SystematicsAsIs;
            //                        num3++;
            //                    }
            //                    else
            //                    {
            //                        property.Systematic = -1.0;
            //                    }
            //                    if (((property.Quality != -1.0) || (property.Quantity != -1.0)) || (property.Systematic != -1.0))
            //                    {
            //                        list.Add(property);
            //                    }
            //                }
            //            }
            //        }
            //    }
            //    this.m_iCountQuality = num;
            //    this.m_iCountQuantity = num2;
            //    this.m_iCountSystematic = num3;
            //}
            //catch (Exception exception)
            //{
            //    flag = false;
            //    Log.LogException(exception);
            //}
            //finally
            //{
            //    if (!flag)
            //    {
            //        list.Clear();
            //    }
            //}
            return list.ToArray();
        }
        
        public void ReadOptions()
        {
            base.ReadGeneralDisplayOptions(eChartType.BarChartQQS);
            this.ReadOwnDisplayOptions();
        }

        private void ReadOwnDisplayOptions()
        {
            try
            {
                //todo
                this.FilterFactorType = FactorType.BK;// base.MapFilterFactorTypeString(oProject.Params.ChartDisplayOptions[eChartType.BarChartQQS.ToString() + ".FilterFactorType"]);
            }
            catch (Exception exception)
            {
                Log.LogException(exception);
            }
        }

        protected override SeriesCollection SetData(ref int riNumberOfElements)
        {
            SeriesCollection seriess = new SeriesCollection();
            riNumberOfElements = 0;
            try
            {
                Series oSeries = new Series
                {
                    Name = ChartCtrl.GetDimensionDescription(eWBDimension.Quantity)
                };
                oSeries.DefaultElement.Color = VMConfig.Intance.Colors.QN;
                if (VMConfig.Intance.Charts.BarChartHatching)
                {
                    oSeries.DefaultElement.HatchStyle = HatchStyle.BackwardDiagonal;
                }
                Series series2 = new Series
                {
                    Name = ChartCtrl.GetDimensionDescription(eWBDimension.Quality)
                };
                series2.DefaultElement.Color = VMConfig.Intance.Colors.QL;
                if (VMConfig.Intance.Charts.BarChartHatching)
                {
                    series2.DefaultElement.HatchStyle = HatchStyle.Cross;
                }
                Series series3 = new Series
                {
                    Name = ChartCtrl.GetDimensionDescription(eWBDimension.Systematic)
                };
                series3.DefaultElement.Color = VMConfig.Intance.Colors.SY;
                if (VMConfig.Intance.Charts.BarChartHatching)
                {
                    series3.DefaultElement.HatchStyle = HatchStyle.ForwardDiagonal;
                }
                this.m_aFactorProperties = this.GetFactorProperties();
                this.m_aFactorProperties.Reverse();
                foreach (FactorProperty property in this.m_aFactorProperties)
                {
                    this.AddElementToSeries(ref series3, property.Systematic, property);
                    this.AddElementToSeries(ref series2, property.Quality, property);
                    this.AddElementToSeries(ref oSeries, property.Quantity, property);
                }
                riNumberOfElements = (oSeries.Elements.Count + series2.Elements.Count) + series3.Elements.Count;
                seriess.Add(new Series[] { series3, series2, oSeries });
                if (this.m_iCountQuantity > 0 || true)//luon hien thi
                {
                    oSeries.LegendEntry.Visible = true;
                    oSeries.LegendEntry.SortOrder = 1;
                    oSeries.LegendEntry.LabelStyle.Font = new Font("Arial", 9f, FontStyle.Regular);
                    oSeries.LegendEntry.LabelStyle.Color = Color.Black;
                }
                else
                {
                    oSeries.LegendEntry.Visible = false;
                }
                if (this.m_iCountQuality > 0 || true)//luon hien thi
                {
                    series2.LegendEntry.Visible = true;
                    series2.LegendEntry.SortOrder = 2;
                    series2.LegendEntry.LabelStyle.Font = new Font("Arial", 9f, FontStyle.Regular);
                    series2.LegendEntry.LabelStyle.Color = Color.Black;
                }
                else
                {
                    series2.LegendEntry.Visible = false;
                }
                if (this.m_iCountSystematic > 0 || true)//luon hien thi
                {
                    series3.LegendEntry.Visible = true;
                    series3.LegendEntry.SortOrder = 3;
                    series3.LegendEntry.LabelStyle.Font = new Font("Arial", 9f, FontStyle.Regular);
                    series3.LegendEntry.LabelStyle.Color = Color.Black;
                    return seriess;
                }
                series3.LegendEntry.Visible = false;
            }
            catch (Exception exception)
            {
                seriess.Clear();
                Log.LogException(exception);
            }
            return seriess;
        }

        public void WriteOptions()
        {
            base.WriteGeneralDisplayOptions(eChartType.BarChartQQS);
            this.WriteOwnDisplayOptions();
        }

        private void WriteOwnDisplayOptions()
        {
            try
            {
                //Todo
                //oProject.Params.ChartDisplayOptions[eChartType.BarChartQQS.ToString() + ".FilterFactorType"] = base.MapFilterFactorType(this.FilterFactorType);
            }
            catch (Exception exception)
            {
                Log.LogException(exception);
            }
        }

        public FactorType FilterFactorType
        {
            get
            {
                return this.m_eFilterFactorType;
            }
            set
            {
                this.m_eFilterFactorType = value;
            }
        }
    }
}
